package com.myc.subject.domain.util;

import com.alibaba.fastjson.JSON;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.myc.subject.domain.entity.SubjectCategoryBO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/***
 * 缓存工具类
 */
@Component
public class CacheUtil<K,V> {

    private Cache<String,String> localCache = CacheBuilder.newBuilder()
            .maximumSize(5000).expireAfterWrite(30, TimeUnit.SECONDS).build();

    public List<V> getResult(String cacheKey, Class<V> clazz, Function<String,List<V>> function){
        //定义缓存并根据key查找本地是否有缓存
        List<V> resultList =new LinkedList<>();
        String content = localCache.getIfPresent(cacheKey);
        if(StringUtils.isNotBlank(content)){
            //缓存不为空则到缓存拿到数据放到返回结果列表中
            resultList = JSON.parseArray(content , clazz);
        }else {
            //缓存为空则查询到相应数据放入返回结果列表中并放入缓存
            resultList = function.apply(cacheKey);
            if(!CollectionUtils.isEmpty(resultList)){
                localCache.put(cacheKey,JSON.toJSONString(resultList));
            }
        }
        return resultList;

    }
}
